<?php 
namespace app\api\controller;

use think\Exception;
use think\Controller;
use app\common\exception\BaseException;
use think\facade\Env;
use app\api\model\Project as ProjectModel;

class Project extends Controller {
    public function getList() {
        $data = ProjectModel::all();
        return json([
            "msg"=> "success",
            "code"=> 20000,
            "data"=> $data
        ],200);
    }

    public function addProject() {
        // $root =  Env::get('root_path');
        if($this->request->param('id')) {
            $pro = ProjectModel::get($this->request->param('id'));
        }else {
            $pro = new ProjectModel();
        }
        $file = request()->file('img');
        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->move( './uploads');
      
        if($info){
            // 成功上传后 获取上传信息
            $pro->img = $info->getSaveName();
            $pro->name = $this->request->param('name');
            $pro->introduction = $this->request->param('introduction');
            $pro->create_time = time();
            $pro->update_time = time();
            $data = $pro->save();
            if($data) {
                return json([
                    "msg"=> "success",
                    "code"=>20000
                ],200);
            }
        }else{
            // 上传失败获取错误信息
            echo $file->getError();
        }
    }
    
    public function deleteProject() {
        if(!$this->request->param("id")) {
            return json([
                "msg"=> "没有传专题ID",
                "code"=> 402
            ],200);
        }
        $data = ProjectModel::get($this->request->param("id"));
        $res = $data->delete();
        if($res) {
            return json([
                "msg"=> "success",
                "code"=> 20000
            ],200);
        }else {
            return json([
                "msg"=> "fail",
                "code"=> 10000
            ],200);
        }
    }

    public function updateProject() {
        $data = new ProjectModel();
        $res = $data-save($this->request->param());
        if($res) {
            return json([
                "msg"=> "success",
                "code"=> 20000
            ],200);
        }else {
            return json([
                "msg"=> "fail",
                "code"=> 10000
            ],200);
        }
    }
}